const requestManager = require("./request.js");
const config = require("./config.js")

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 登录
const userLogin = () => {
  // 用于通知外界登录情况.
  return new Promise(function(outResolve, outReject) {
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        // 登录
        getApp().globalData.code = res.code;
        wx.getUserInfo({
          withCredentials: true,
          success: res => {
            // 可以将 res 发送给后台解码出 unionId
            getApp().globalData.userInfo = res.userInfo;
            getApp().globalData.isAuthorize = true;

            //微信数据回调
            if (getApp().userInfoReadyCallback) {
              getApp().userInfoReadyCallback(res)
            }

            let params = {
              code: getApp().globalData.code,
              appId: config.appId,
              userType: 1,
              encryptedData: res.encryptedData,
              iv: res.iv
            }

            requestManager.getDataResult(requestManager.wx_app_login, params, "POST")
              .then(resolve => {
                console.log('resolve.........',resolve)
                getApp().globalData.loginResult = resolve;
                getApp().globalData.userToken = resolve.userToken;
                wx.setStorage({
                  key: 'loginResult',
                  data: resolve,
                })
                // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                // 所以此处加入 callback 以防止这种情况
                if (getApp().loginResultReadyCallback) {
                  getApp().loginResultReadyCallback(resolve)
                }

                outResolve(resolve);

              }, reject => {
                outReject(reject);
              })

          },
          fail: e => {
            outReject(e)
          }
        })
      },

      fail: res => {
        outReject(res)
      }
    })

  })
}

/**
 * 手机号检测
 */
const reg = /^1[3-9][0-9]{9}$/; //手机验证规则
function isPhoneNum(phoneNum) {
  return reg.test(phoneNum);
}

/**
 * 页面间参数处理工具
 * arr 传入数组,两两拼接成字符串
 */
const formatParams = function(arr) {
  var sb = ""
  var ar = []
  ar.length
  if (arr.length > 2) {
    for (var i = 0; i < arr.length; i++) {
      if (i == 0) {
        // 键
        sb = arr[i] + "="
      } else if (i == arr.length - 1) {
        // 值
        sb = sb + arr[i]
      } else if (i % 2 == 0) {
        // 键
        sb = sb + arr[i] + "="
      } else {
        // 值
        sb = sb + arr[i] + "&"
      }
    }
  } else {
    sb = arr[0] + "=" + arr[1]
  }
  return sb
};

/**
 * 获取屏幕高(rpx)
 */
function getWindowHeight() {
  return new Promise(function(resolve, reject) {
    wx.getSystemInfo({
      success: function(res) {
        let clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        let calc = clientHeight * rpxR;
        resolve(calc)
      }
    });

  })
}

/**
 * 获取系统信息
 * 
 * action sync同步获取  async异步获取
 */
function getSystemInfo(action = "sync") {
  if (action == "sync") {
    let systemInfo;
    try {
      // 同步获取数据
      systemInfo = wx.getStorageSync("systemInfo");
      if (systemInfo != undefined && systemInfo != null && systemInfo.screenWidth != undefined && systemInfo.screenWidth != 0) {
        // 有缓存
        return systemInfo;
      } else {
        // 无缓存
        systemInfo = wx.getSystemInfoSync();
        wx.setStorage({
          key: 'systemInfo',
          data: systemInfo,
        })
        return systemInfo;
      }
    } catch (e) {
      return systemInfo;
    }
  } else {
    return new Promise(function(resolve, reject) {
      let systemInfo;
      // 异步获取数据
      wx.getStorage({
        key: 'systemInfo',
        success: function(res) {
          systemInfo = res.data;
          if (systemInfo != undefined && systemInfo != null && systemInfo.screenWidth != undefined && systemInfo.screenWidth != null && systemInfo.screenWidth != 0) {
            resolve(systemInfo)
          } else {
            wx.getSystemInfo({
              success: function(res) {
                systemInfo = res;
                wx.setStorage({
                  key: 'systemInfo',
                  data: systemInfo,
                })
                resolve(systemInfo)
              },
              fail: function(res) {
                reject(systemInfo)
              }
            })
          }
        },

        fail: function(res) {
          wx.getSystemInfo({
            success: function(res) {
              systemInfo = res;
              wx.setStorage({
                key: 'systemInfo',
                data: systemInfo,
              })
              resolve(systemInfo)
            },
            fail: function(res) {
              reject(systemInfo)
            }
          })
        }
      })
    })
  }
}

/**
 * Toast工具
 */
function noIconToast(msg, duration = 1500) {
  if (typeof msg == "string" && msg != "") {
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: duration,
    })
  }
}

/**
 * 加载中状态显示
 * 
 * 默认显示蒙层,防止点击
 */
function showLoading(title = "", mask = true) {
  if (typeof title == "string") {
    wx.showLoading({
      title: title,
      mask: mask
    })
  }
}

/**
 * 用于从内存或缓存获取用户登录信息
 */
function getUserInfo() {
  let loginResult = getApp().globalData.loginResult;
  let userId;
  if (loginResult != null && loginResult != undefined) {
    userId = loginResult.userId;
  }
  if (userId != undefined && userId != null && userId != 0) {
    return loginResult;
  } else {
    try {
      loginResult = wx.getStorageSync("loginResult")
      userId = loginResult.userId
      if (userId != undefined && userId != null && userId != 0) {
        return loginResult
      } else {
        userLogin();
        return {
          userId: 0,
          mobile: "",
          userToken: ""
        }
      }
    } catch (e) {
      userLogin();
      return {
        userId: 0,
        mobile: "",
        userToken: ""
      }
    }
  }
}

/**
 * 将用户登录信息存入内存及缓存
 */
function setUserInfo(loginResult) {
  getApp().globalData.loginResult = loginResult;
  wx.setStorage({
    key: 'loginResult',
    data: loginResult,
  })
}

// 后台自定义事件上报
function reportAnalytics(cssName, params = {}) {
  // 事件上报基础信息(用户ID,用户微信昵称)
  let reportBaseObj = {
    user_id: getUserInfo().userId,
    user_name: getApp().globalData.userInfo != undefined ? getApp().globalData.userInfo != null ? getApp().globalData.userInfo.nickName != undefined ? getApp().globalData.userInfo.nickName != null ? getApp().globalData.userInfo.nickName : "" : "" : "" : "",
  }

  // 微信后台自定义事件统计
  wx.reportAnalytics(cssName, Object.assign(reportBaseObj, params));

  // 阿拉丁统计
  getApp().aldstat.sendEvent(cssName, Object.assign(reportBaseObj, params));
}

/**
 * log工具
 */
function log(name, value) {
  if (config.showLog) {
    console.log(name, value)
  }
}

//表单id
function formSubmit(e) {
  if (getApp().globalData.loginResult == null || getApp().globalData.loginResult.userId == null || typeof getApp().globalData.loginResult.userId == undefined || getApp().globalData.loginResult.userId == '') {
    return;
  }
  let formId = e.detail.formId;
  let params = {
    userType: 1,
    userId: getApp().globalData.loginResult.userId,
    formId: formId,
    appId: config.appId
  }

  let turnTag = e.detail.target.dataset.turnTag;
  if (turnTag != undefined && turnTag != "") {
    let unNecessaryParam = {
      turnTag: turnTag
    };
    Object.assign(params, unNecessaryParam)
  }
  requestManager.getDataResult(requestManager.wx_app_form_id, params, "POST")
}

function isEmojiCharacter(substring) {
  for (var i = 0; i < substring.length; i++) {
    var hs = substring.charCodeAt(i);
    if (0xd800 <= hs && hs <= 0xdbff) {
      if (substring.length > 1) {
        var ls = substring.charCodeAt(i + 1);
        var uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
        if (0x1d000 <= uc && uc <= 0x1f77f) {
          return true;
        }
      }
    } else if (substring.length > 1) {
      var ls = substring.charCodeAt(i + 1);
      if (ls == 0x20e3) {
        return true;
      }
    } else {
      if (0x2100 <= hs && hs <= 0x27ff) {
        return true;
      } else if (0x2B05 <= hs && hs <= 0x2b07) {
        return true;
      } else if (0x2934 <= hs && hs <= 0x2935) {
        return true;
      } else if (0x3297 <= hs && hs <= 0x3299) {
        return true;
      } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 ||
        hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b ||
        hs == 0x2b50) {
        return true;
      }
    }
  }
}

/**
 * 获取地址信息
 */
function getLocationInfo() {
  let locationInfo = new Object();
  let globalData = getApp().globalData;

  if (globalData.city != undefined && globalData.city != null && globalData.city.cityId != undefined && globalData.city.cityId != 0) {
    locationInfo.city = globalData.city
  } else {
    locationInfo.city = {
      cityId: 0,
      cityName: "",
    }
  }

  if (globalData.latitude != undefined && globalData.latitude != null && globalData.latitude != 0) {
    locationInfo.latitude = globalData.latitude
  } else {
    locationInfo.latitude = 0
  }

  if (globalData.longitude != undefined && globalData.longitude != null && globalData.longitude != 0) {
    locationInfo.longitude = globalData.longitude
  } else {
    locationInfo.longitude = 0
  }

  return locationInfo;
}

//深拷贝
function deepCopy(obj) {
  if (obj == undefined) {
    return undefined;
  }
  if (typeof obj != 'object') {
    return obj;
  }
  let newobj = {};
  for (var attr in obj) {
    newobj[attr] = this.deepCopy(obj[attr]);
  }
  return newobj;
}

/**
 * 对手机号有效性进行判断
 */
function checkUserMobile(mobile, onSuccess, onFailed) {
  let params = {
    userId: getUserInfo().userId,
    mobile: mobile
  }
  requestManager.getDataResult(requestManager.mobile_usability_check, params, "POST")
    .then(data => {
      onSuccess(data);
    }, e => {
      onFailed(e);
      noIconToast(e.msgContent);
    })
}

module.exports = {
  formatTime: formatTime,
  userLogin: userLogin,
  formatParams: formatParams,
  getWindowHeight: getWindowHeight,
  noIconToast: noIconToast,
  getUserInfo: getUserInfo,
  log: log,
  formSubmit: formSubmit,
  isEmojiCharacter: isEmojiCharacter,
  reportAnalytics: reportAnalytics,
  getLocationInfo: getLocationInfo,
  getSystemInfo: getSystemInfo,
  showLoading: showLoading,
  deepCopy: deepCopy,
  setUserInfo: setUserInfo,
  isPhoneNum: isPhoneNum,
  checkUserMobile: checkUserMobile
}